package ServletDemo2;

import entity.Books;
import javax.servlet.ServletException;
import util.GokJDBCUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/addBookServlet")
public class addBookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public addBookServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求的编码
        request.setCharacterEncoding("UTF-8");

        // 获取表单提交的数据
        String bookName = request.getParameter("bookName");
        String category = request.getParameter("category");
        String author = request.getParameter("author");
        String publisher = request.getParameter("publisher");
        String language = request.getParameter("language");
        Double price = Double.parseDouble(request.getParameter("price"));
        String publishDate = request.getParameter("publish_date");

        // 插入数据到数据库
        String sql = "INSERT INTO books (bookName, category, author, publisher, language, price, publish_date) VALUES (?, ?, ?, ?, ?, ?, ?)";
        int result = GokJDBCUtil.update(sql, bookName, category, author, publisher, language, price, publishDate);

        // 根据插入结果跳转页面或显示提示信息
        if (result > 0) {
            // 添加成功，重定向到图书列表页面
            response.sendRedirect("home.jsp");
        } else {
            // 添加失败，返回错误信息并跳转回添加页面
            request.setAttribute("errorMsg", "添加图书失败，请重试！");
            request.getRequestDispatcher("addBookPage.jsp").forward(request, response);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
    }
}